package com.sff.easyexcel.test.demo.template;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.google.common.collect.Sets;
import com.sff.easyexcel.test.demo.merge.CellMergeStrategy;
import com.sff.easyexcel.test.demo.util.FilePathUtil;
import lombok.Data;
import org.apache.commons.compress.utils.Lists;

import java.math.BigDecimal;
import java.util.List;

/**
 * 订单号合并导出
 * 1.excel 导出合并策略
 * https://blog.csdn.net/weixin_50067580/article/details/111559637
 */
public class MergeCellDataByOrderId {

    public static void main(String[] args) {

        String writeFileName = FilePathUtil.getPath() + "order-id-" + System.currentTimeMillis() + ".xlsx";

        /**从哪行开始合并*/
        int mergeRowIndex = 1;

        ExcelWriter writer = null;
        try {
            writer = EasyExcel.write(writeFileName, Order.class)
                    .registerWriteHandler(new CellMergeStrategy(0, mergeRowIndex, Sets.newHashSet(0, 1)))
                    .build();

            WriteSheet writeSheet = EasyExcel.writerSheet("订单信息").build();

            writer.write(createData(), writeSheet);
        } finally {
            if (writer != null) {
                writer.finish();
            }
        }
    }

    private static List<Order> createData() {

        List<Order> orderList = Lists.newArrayList();
        Order order = new Order();
        String orderId = "A" + System.currentTimeMillis();
        order.setOrderId(orderId);
        order.setName("西红柿鸡蛋");
        order.setCount(2);
        order.setPrice(BigDecimal.valueOf(8.35));
        orderList.add(order);

        Order order1 = new Order();
        order1.setOrderId(orderId);
        order1.setName("西红柿鸡蛋1");
        order1.setCount(4);
        order1.setPrice(BigDecimal.valueOf(12.35));
        orderList.add(order1);

        return orderList;
    }

    @Data
    private static class Order {
        @ExcelProperty(value = "订单编号", index = 0)
        private String orderId;

        @ExcelProperty(value = "商品名称", index = 1)
        private String name;

        @ExcelProperty(value = "商品价格", index = 2)
        private BigDecimal price;

        @ExcelProperty(value = "商品数量", index = 3)
        private Integer count;
    }

}
